<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="450" destroy-on-close @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" ref="dialogFormRef" label-width="120px" label-position="left">
            <el-form-item label="文件夹名称" prop="name">
                <el-input v-model="form.name" clearable placeholder="请输入文件夹名称"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, computed, inject } from 'vue';
import api from '@/api';
import { ElMessage } from 'element-plus';

// 获取全局注入的工具对象和路由实例
const $TOOL = inject('$TOOL');
const emit = defineEmits(['success', 'closed']);
const mode = ref('add');
const visible = ref(false);
const titleMap = reactive({ add: '创建文件夹' });
const form = reactive({ id: '', pid: 0, user_id: '', name: '' });
const rules = computed(() => ({ name: [{ required: true, message: '请输入文件夹名称', trigger: 'blur' }] }));
const isSaveing = ref(false);
const dialogFormRef = ref(null);

const open = (newMode = 'add', pid) => {
    mode.value = newMode;
    form.pid = pid;
    form.user_id = $TOOL.data.get('USER_INFO').id;
    visible.value = true;
};
const submit = async () => {
    dialogFormRef.value.validate(async (valid) => {
        if (!valid) return false;
        isSaveing.value = true;
        const res = await api.common.folder.add.post(form);
        if (res.code === 200) {
            emit('success', mode.value);
            visible.value = false;
            ElMessage.success(res.message);
        } else {
            ElMessage.error(res.message);
        };
        isSaveing.value = false;
    });
};
//表单注入数据
const setData = (data) => {
    form.id = data.id
    form.pid = data.pid
    form.name = data.name
}
defineExpose({ open, setData });
</script>